<?php

class help extends bhCommon {


    /**
     * 发起砍价
     */
    public function launch()
    {
        $goods_id = intval($this->get('goods_id'));

        $sql = "SELECT id FROM " . prefix('order') . " WHERE member_id={$this->member['id']} AND goods_id={$goods_id} AND `status`=1 AND time_end >" . time();
        $order = p_fetch($sql);

        if ($order) {
            $this->json(array('id' => $order['id']));
        }
        $goods = p_get('goods', array('id' => $goods_id, 'status' => 1, 'is_delete' => 1));
        if (empty($goods)) {
            $this->json('商品不存在或已下架', 2);
        }

        if ($goods['is_first'] == 2 && p_getcolumn('order', array('member_id' => $this->member['id']), 'COUNT(*)')) {
            $this->json('您已不是首次,请选择非首次砍价商品', 2);
        }

        $number = p_getcolumn('order', array('goods_id' => $goods_id, 'status' => 2), 'COUNT(*)') ? : 0;

        if ($number >= $goods['stock']) {
            $this->json('库存不足', 2);
        }

        $insert = array(
            'member_id' => $this->member['id'],
            'goods_id' => $goods_id,
            'price' => $goods['price'],
            'integral' => $goods['integral'],
            'time_start' => time(),
            'time_end' => time() + $goods['bargain_time'],
        );

        if (p_insert('order', $insert)) {
            $this->json(array('id' => pdo_insertid()));
        }

        $this->json('发起失败', 2);
    }


    /**
     * 详情
     */
    public function details()
    {
        $id = $this->get('id');

        $order = p_get('order', array('id' => $id));
        if (empty($order)) {
            $this->json('砍价不存在', 0);
        }

        $is_my = $order['member_id'] == $this->member['id'];
        $goods = p_get('goods', array('id' => $order['goods_id']));
        $goods['cover_image'] = getImage($goods['cover_image']);

        $goods['share_txt'] = str_replace('{name}', $this->member['nickname'], $goods['share_txt']);

        $launch = p_get('member', array('id' => $order['member_id']));
        $order['surplus'] = round($order['price'] - $order['bargain'], 2);
        if ($order['bargain'] > $goods['in_after']) {
            $need = ceil(($order['price'] - $order['bargain']) / $goods['new_after_start']);
        } else {
            $need = ceil(($order['price'] - $order['bargain']) / $goods['new_start']);
        }

        $order['percentage'] = floor(($order['bargain'] / $order['price']) * 100);


        $config = array(
            'bargain_describe' => getConfig('bargain_describe', '“我发现了一件好货，快来帮我砍价吧！”'),
            'integral_name' => getConfig('integral_name', '积分'),
            'special_reminder' => getConfig('special_reminder', '下单后6个工作日内发货, 新疆、西藏、内蒙古、港澳台地区暂不支持'),
            'video_id' => getConfig('video_id'),
            'screen_id' => getConfig('screen_id'),
            'is_bargain_video' => getConfig('is_bargain_video', 1),
            'bargain_style' => getConfig('bargain_style', '#fa0034'),
            'video_ad_id' => getConfig('bargain_ad'),
            'show_share_people' => getConfig('show_share_people', 1),
            'dy_bargaining_process_id' => getConfig('dy_bargaining_process_id'),
            'single_ad' => getConfig('single_ad'),
            'bargain_demo_time' => getConfig('bargain_demo_time'),
            'bargain_demo_appid' => getConfig('bargain_demo_appid'),
        );


        $coupon = array();
        $is_bargain = p_get('order_bargain', array('member_id' => $this->member['id'], 'order_id' => $id));
        if (!$is_my) {
            $config['every_day_number'] = $this->bargain->get_bargain_number($this->member['id']);

        } else if ($order['coupon_id'] == 0) {
            $sql = 'SELECT A.id,A.coupon_id,A.expire,B.type,B.name,B.icon,B.worth FROM ' . prefix('member_coupon') . ' AS A INNER JOIN ' . prefix('coupon') . ' AS B ON A.coupon_id=B.id WHERE A.member_id=' . $this->member['id'] . ' AND A.is_use=1 AND A.expire>' . time();

            $coupon = p_fetchall($sql);
            $coupon = arrayImage($coupon, 'icon');
        }

        $sql = 'SELECT id,cover_image,is_first,name,bargain_number,integral FROM ' . prefix('goods') . " WHERE category_id={$goods['category_id']} AND id!={$goods['id']} AND is_delete=1 AND status=1 ORDER BY sort DESC";

        $goods_list = p_fetchall($sql);
        $goods_list = arrayImage($goods_list, 'cover_image');

        //砍价剩余时间
        $order['surplus_time'] = $order['time_end'] - time();

        $data = array(
            'is_my' => $is_my,
            'order' => $order,
            'launch' => $launch,
            'need' => $need,
            'config' => $config,
            'goods' => $goods,
            'goods_list' => $goods_list,
            'is_bargain' => $is_bargain,
            'coupon' => $coupon,
            'is_auth' => $this->is_auth
        );
        $this->json($data);
    }


    /**
     * 砍价列表
     */
    public function help_list()
    {
        $id = intval($this->get('id'));

        $sql = 'SELECT A.money,B.nickname,B.headimgurl FROM ' . prefix('order_bargain') . ' AS A INNER JOIN ' . prefix('member') . ' AS B ON A.member_id=B.id WHERE A.order_id=' . $id . ' ORDER BY A.id DESC';
        $help_list = p_fetchall($sql);

        $data = array(
            'help_list' => $help_list
        );
        $this->json($data);
    }


    /**
     * 砍价成功列表
     */
    public function help_succ()
    {
        $id = intval($this->get('id'));

        $sql = "SELECT A.suc_time,B.nickname,B.headimgurl FROM " . prefix('order') . " AS A LEFT JOIN " . prefix('member') . " AS B ON A.member_id=B.id WHERE A.goods_id={$id} AND A.status=2";
        $help_succ = p_fetchall($sql);//var_dump($sql);

        foreach ($help_succ as & $value) {
            $value['suc_time'] = formatTime($value['suc_time']);
        }

        $data = array(
            'help_succ' => $help_succ
        );
        $this->json($data);
    }


    /**
     *  帮助砍价
     */
    public function bargain()
    {
        $id = intval($this->get('id'));

        $flag = $this->bargain->bargaining($id, $this->member['id']);
        if ($flag) {
            $this->json(array('money' => $flag));
        } else {
            $this->json($this->bargain->error, 2);
        }
    }


    /**
     * 使用道具
     */
    public function useCoupon()
    {
        $order_id = intval($this->get('order_id'));
        $coupon_id = intval($this->get('coupon_id'));


        $where = array(
            'id' => $order_id,
            'member_id' => $this->member['id']
        );
        $order = p_get('order', $where);
        if (empty($order)) {
            $this->json('砍价订单不存在', 2);
        }
        if ($order['status'] == 2 || $order['time_end'] < time()) {
            $this->json('砍价已结束', 2);
        }


        $coupon = p_get('member_coupon', array('id' => $coupon_id));
        if (empty($coupon)) {
            $this->json('道具不存在', 2);
        }
        if ($coupon['is_use'] == 2 || $coupon['expire'] < time()) {
            $this->json('道具已被使用或者已过期', 2);
        }

        $c = p_get('coupon', array('id' => $coupon['coupon_id']));

        pdo_begin();
        try{
            $time_end = $order['time_end'] + ($c['worth'] * 86400);

            $u = array(
                'time_end' => $time_end,
                'coupon_id' => $coupon_id
            );
            if (!p_update('order', $u, array('id' => $order_id))) {
                throw new Exception('道具使用失败');
            }
            $u = array(
                'is_use' => 2,
                'use_time' => time(),
                'order_id' => $order_id
            );
            if (!p_update('member_coupon', $u, array('id' => $coupon_id))) {
                throw new Exception('道具使用失败');
            }
            pdo_commit();
            $this->json();
        } catch (Exception $e) {
            pdo_rollback();
            $this->json($e->getMessage(), 2);
        }
    }


    /**
     * 海报
     */
    public function poster()
    {
        //$bargain_poster_bg = $this->images('bargain_poster_bg', 'm1iIbB4e40E0T0Tw0KeZEkNZKbN0kD.jpg');
        $bargain_poster_bg = getConfig('bargain_poster_bg');
        if ($bargain_poster_bg) {
            $bargain_poster_bg = getImageLocal($this, $bargain_poster_bg);
        } else {
            $bargain_poster_bg = $this->image_url . 'm1iIbB4e40E0T0Tw0KeZEkNZKbN0kD.jpg';
        }

        $order_id = intval($this->get('id'));

        $order = p_get('order', array('id' => $order_id));
        $goods = p_get('goods', array('id' => $order['goods_id']));
        //$goods['cover_image'] = getImage($goods['cover_image']);

        $goods['cover_image'] = getImageLocal($this, $goods['cover_image']);


        $name = $order_id . '-' . $this->member['id'];

        $code = createWxCode($this, $name, 'bh_bargain/pages/bargain/bargain', 'k-'. $name . '.png');

        //$this->member['headimgurl'] = headLocal($this, $this->member['headimgurl']);

        $data = array(
            'order' => $order,
            'goods' => $goods,
            'code' => $code,
            'member' => $this->member,
            'bargain_poster_bg' => $bargain_poster_bg,
            'poster_txt' => getConfig('poster_txt', '我已经砍了4件商品了,全场包邮快来一起砍吧')
        );
        $this->json($data);
    }

}